package cn.passlink.bletoothchat.mFragment;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.passlink.bletoothchat.Adapter.ScanFriendsAdapter;
import cn.passlink.bletoothchat.BleGATT.ClientUtils;
import cn.passlink.bletoothchat.R;
import cn.passlink.bletoothchat.SqlTables.FriendsTableManager;
import cn.passlink.bletoothchat.SqlTables.MyDatabaseHelper;
import cn.passlink.bletoothchat.mActivity.AddFriendsActivity;
import cn.passlink.bletoothchat.mActivity.FriendTalkingActivity;
@SuppressLint("MissingPermission")
public class AddFriendsScrollingFragment extends Fragment {

    private SQLiteDatabase database;
    private MyDatabaseHelper databaseHelper;
    private Context mContext;
    private AddFriendsActivity mAddFriendsActivity;

    List<BluetoothDevice> scannedDevices = new ArrayList<>();

    private ScanFriendsAdapter adapter;
    private myViewModel myViewModel;
    private ClientUtils clientUtils; // 蓝牙客户端工具

    @Nullable

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_add_friends_scrolling, container, false);

        myViewModel = new ViewModelProvider(requireActivity()).get(myViewModel.class);
        // 观察设备列表的变化
        myViewModel.getDevicesLiveData().observe(getViewLifecycleOwner(), new Observer<List<BluetoothDevice>>() {
            @Override
            public void onChanged(List<BluetoothDevice> devices) {
                // 更新适配器
                updateDevices(devices);
            }
        });

        // 初始化 databaseHelper
        mContext = getContext();
        databaseHelper = new MyDatabaseHelper(mContext, 2);
        database = databaseHelper.getWritableDatabase();

        return mView;


    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ImageView searchButton = (ImageView) view.findViewById(R.id.search_friends_imageView);
        TextView crete_text = (TextView) view.findViewById(R.id.search_friends_editText);
        // 找到 ListView 对象
        ListView listView = view.findViewById(R.id.search_friends_ListView);
        adapter = new ScanFriendsAdapter(mContext, scannedDevices,clientUtils);
        // 设置适配器
        listView.setAdapter(adapter);
        //搜索好友
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 初始化 databaseHelper

                FriendsTableManager mFriendsTableManager = new FriendsTableManager(database);

                //构造数据

            }

        });


    }
//更新设备
    public void updateDevices(List<BluetoothDevice> devices) {
        // 去重处理
        for (BluetoothDevice device : devices) {
            boolean isDuplicate = false;
            for (BluetoothDevice scannedDevice : scannedDevices) {
                if (scannedDevice.getAddress().equals(device.getAddress())) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate) {
                scannedDevices.add(device);
            }
        }
        //有名字的排前
        Collections.sort(scannedDevices, new Comparator<BluetoothDevice>() {
            @Override
            public int compare(BluetoothDevice device1, BluetoothDevice device2) {
                if (device1.getName() != null && device2.getName() == null) {
                    return -1; // device1有名字，device2无名字，将device1排在前面
                } else if (device1.getName() == null && device2.getName() != null) {
                    return 1; // device1无名字，device2有名字，将device2排在前面
                } else {
                    return 0; // device1和device2都有名字或都无名字，不做调整
                }
            }
        });

        adapter.notifyDataSetChanged(); // 通知适配器更新数据
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (database != null) {
            database.close();
        }
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof AddFriendsActivity) {
            mAddFriendsActivity = (AddFriendsActivity) context; // 获取扫描活动的引用
            clientUtils = mAddFriendsActivity.getClientUtils(); // 获取蓝牙客户端工具的引用
        }
    }
    public void goToTargetActivity(String whoName,String phone) {

//      // 创建 Intent
        Intent intent = new Intent(getActivity(), FriendTalkingActivity.class);
        // 传递数据（可选）
        intent.putExtra("whoName", whoName);
        intent.putExtra("whoPhone", phone);
        // 启动 Activity
        startActivity(intent);
    }

}